#include "HardwareProfile.h"
_CP1616_Client_Flags CP1616_Client_Flags;
unsigned char CP1616_Client_RxList[MAX_CP1616_Client_RX];
unsigned char CP1616_Client_RxCount;
unsigned char CP1616_Client_NeedRxCount;
unsigned int CP1616_Client_NoRxTick;
void CP1616_Client_Init(void)
{
	CP1616_Client_EndProcCommand();
	//SetCOM1TX();
//	/while(1)
//	{
//		Uart_PutChar(0xff);
//	}
}
void CP1616_Client_EndProcCommand(void)
{
	CP1616_Client_Flags.bRx=0;
	CP1616_Client_NeedRxCount=0xff;
	CP1616_Client_RxCount=0;
}
void CP1616_Client_ProcRx(unsigned char rx)
{
	CP1616_Client_NoRxTick=SystemTick;
	if(CP1616_Client_Flags.bRx==1)
		return;
	CP1616_Client_RxList[CP1616_Client_RxCount++]=rx;
	if(CP1616_Client_RxCount>pCP1616_ClientData)
	{
		if(rx==0x0d && CP1616_Client_RxCount==CP1616_Client_NeedRxCount)
		{			
			CP1616_Client_Flags.bRx=1;			
		}
		else if(CP1616_Client_RxCount>CP1616_Client_NeedRxCount)
		{
			CP1616_Client_RxCount=0;
			CP1616_Client_NeedRxCount=0xff;
		}
		else if(CP1616_Client_RxCount>MAX_CP1616_Client_RX)
		{
			CP1616_Client_RxCount=0;
			CP1616_Client_NeedRxCount=0xff;				
		}
	}
	else if(CP1616_Client_RxCount==pCP1616_ClientData)
	{
		CP1616_Client_NeedRxCount=CP1616_Client_RxList[3]+6;
	}
	else if(CP1616_Client_RxCount==2)
	{
		if(rx!=0x16)
		{
			CP1616_Client_RxCount=0;
		}
	}
	else if(CP1616_Client_RxCount==1)
	{
		if(rx!=0x16)
		{
			CP1616_Client_RxCount=0;
		}
	}	
}
void CP1616_Client_SendData(unsigned char CommandIndex,unsigned char* pBuff,unsigned char Count)
{
	unsigned char sum;
	unsigned char i;
	sum=0;
	CP1616_Client_AddTxHeader();
	CP1616_Client_TxByteWithVerify(CommandIndex);
	CP1616_Client_TxByteWithVerify(Count);
	for(i=0;i<Count;i++)
	{
		CP1616_Client_TxByteWithVerify(pBuff[i]);
	}
	CP1616_Client_AddTxEnder();
	CP1616_Client_EndProcCommand();
}
void CP1616_Client_SendOK(unsigned char CommandIndex)
{
	unsigned char sum;
	sum=0;
	CP1616_Client_AddTxHeader();
	CP1616_Client_TxByteWithVerify(CommandIndex);
	CP1616_Client_TxByteWithVerify(0x02);
	CP1616_Client_TxByteWithVerify('O');
	CP1616_Client_TxByteWithVerify('K');
	CP1616_Client_AddTxEnder();
	CP1616_Client_EndProcCommand();
}

void CP1616_Client_SendError( unsigned char CommandIndex )
{
	unsigned char sum;
	sum=0;
	CP1616_Client_AddTxHeader();
	CP1616_Client_TxByteWithVerify(CommandIndex);
	CP1616_Client_TxByteWithVerify(0x03);
	CP1616_Client_TxByteWithVerify('E');
	CP1616_Client_TxByteWithVerify('R');
	CP1616_Client_TxByteWithVerify('R');
	CP1616_Client_AddTxEnder();
	CP1616_Client_EndProcCommand();
}

